package com.an.vhr.utils;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;

/**
 * @Author: an1089
 **/
public class FastDFSUtil {
    private static StorageClient1 storageClient1;
    static {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            storageClient1 = new StorageClient1(trackerServer, null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    public static String upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        try {
            String uploadUrl = storageClient1.upload_appender_file1(file.getBytes(), originalFilename.substring(originalFilename.lastIndexOf(".") + 1), null);
            String s = uploadUrl.substring(uploadUrl.indexOf("/") + 1);
            int second = (int) Instant.now().getEpochSecond();
            String token = ProtoCommon.getToken(s, second, "FastDFSan");
            StringBuffer sb = new StringBuffer();
            sb.append("http://192.168.12.128/")
                    .append(uploadUrl)
                    .append("?token=")
                    .append(token)
                    .append("&ts=")
                    .append(second);
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


}
